import { test, expect } from '@playwright/test';
import { searchExcept } from './getData.js';

// 搜索
export const search = async (page, url, searchParams) => {
  await page.getByRole('button', { name: '搜 索' }).click();
  let data = await getDataList(page, url);
  let resultData = data.data;
  await page.waitForTimeout(2000);
  // 遍历数组中的每个搜索字段配置对象
  for (let { name, prop, apiProp, type = 'input', options } of searchParams) {
    if (resultData && resultData.length > 0) {
      const apiKey = apiProp || prop;
      const value = resultData[0][apiKey];
      if (value) {
        if (type === 'input') {
          // 输入框的搜索处理
          await page.getByPlaceholder(`请输入 ${name}`, { exact: true }).fill(value);
        } else if (type === 'select') {
          // 下拉框的搜索处理
          const selectLocator = page.getByPlaceholder(`请选择 ${name}`, { exact: true });
          await selectLocator.click();
          await page.waitForSelector('.el-select-dropdown__item:visible');
          //  映射接口返回的值到下拉框显示的文本
          const optionText = options ? options[value] : value;
          await page.locator(`.el-select-dropdown__item:has-text("${optionText}")`).nth(0).click();
        } else if (type === 'datetimerange') {
          await handleDateTimeRange(page, value, name); // 处理日期范围类型
        } else if (type === 'date') {
          await handleDateSelection(page, value, name); // 处理日期类型
        }
        // 点击搜索按钮
        await page.getByRole('button', { name: '搜 索' }).click();
        // 校验搜索结果
        console.log(`搜索名称: ${name}\n` + `API字段: ${apiKey}\n` + `搜索值: ${value}\n` + `-----------------------------------`);
        await searchExcept(url, page, apiKey, value, type);
      } else {
        console.log(`搜索名称: ${name}\n` + `API字段: ${apiKey}\n` + `搜索值: null\n` + `-----------------------------------`);
      }
    }
  }
};

// 详情
export const detail = async (page, url) => {
  await page.locator('.el-table__fixed-right .el-table__fixed-body-wrapper .el-table__row .el-icon-view').first().click();
  await page.waitForResponse((res) => res.url().includes(url) && res.status() === 200);
};

// 通用删除函数：根据rowsToDelete决定单行删除还是批量删除
export const del = async (page, url, rowsToDelete = 1) => {
  // 1. 搜索并获取当前数据列表
  await page.getByRole('button', { name: '搜 索' }).click();
  let data = await getDataList(page, url);
  let startLen = data.length;

  if (rowsToDelete > 1) {
    // 2. 勾选多行数据
    for (let i = 0; i < rowsToDelete; i++) {
      await page.locator('.el-table__fixed-body-wrapper .el-table__row .el-table-column--selection:visible').nth(i).click();
    }
  } else {
    // 单行删除
    await page.locator('.el-table__fixed-right .el-table__fixed-body-wrapper .el-table__row .el-icon-delete').first().click();
  }
  // 3. 点击删除按钮并确认删除
  if (rowsToDelete > 1) {
    await page.locator('button:has-text("删 除") .el-icon-delete').click();
  }
  await page.getByRole('button', { name: '确定' }).click();

  // 4. 验证数据减少了相应的行数
  let data2 = await getDataList(page, url);
  let endLen = data2.length;
  expect(startLen - endLen).toBe(rowsToDelete);
};

// 必填项检验 rfv:Required Field Validation
export const rfv = async (page, formSelector, requiredFields) => {
  // 提交表单
  await page.click(`${formSelector} .avue-dialog__footer .el-button--primary`);

  // 遍历必填项提示信息列表，验证是否可见
  for (const message of requiredFields) {
    await expect(page.locator(`text=${message}`)).toBeVisible();
  }

  // 关闭表单
  await page.click(`${formSelector} .avue-dialog__footer .el-button--default`);
};

// 获取分页数据
const getDataList = async (page, url) => {
  const promise = await page.waitForResponse((res) => {
    return res.url().includes(url);
  });
  const res = await promise;
  const data = await res.json();
  return {
    length: data.data.total,
    data: data.data.records
  };
};

async function handleDateTimeRange(page, value, name) {
  let baseTime = value.split(' ')[0];
  let Year = baseTime.split('-')[0];
  let Month = Number(baseTime.split('-')[1]);
  let Day = Number(baseTime.split('-')[2]);

  const selectLocator = page.locator(`[content="请选择 ${name}"]`);
  await selectLocator.click();

  const today = new Date(); // 获取当前日期
  const nowYear = today.getFullYear(); // 获取年份
  const nowMonth = Number(String(today.getMonth() + 1).padStart(2, '0')); // 获取月份（注意：月份是从0开始的，因此要加1）

  console.log(Year, Month, Day, '测试值');

  await setDate(Year, Month, Day);

  // 年逻辑
  async function navigateToYear(Year) {
    const direction = Year > nowYear ? 'right' : 'left';
    const yearDiff = Math.abs(Year - nowYear);
    for (let i = 0; i < yearDiff; i++) {
      await page.locator(`.el-picker-panel__content.is-${direction} .el-date-range-picker__header button:visible`).nth(0).click();
    }
  }

  // 月日逻辑
  async function navigateToMonthAndDay(Month, Day) {
    const direction = Month > nowMonth ? 'right' : 'left';
    const monthDiff = Math.abs(Month - nowMonth);
    for (let i = 0; i < monthDiff; i++) {
      await page.locator(`.el-picker-panel__content.is-${direction} .el-date-range-picker__header button:visible`).nth(1).click();
    }
    await page
      .locator('.el-picker-panel__content.is-left .el-date-table__row .available:visible')
      .nth(Day - 1)
      .dblclick();
  }

  async function setDate(Year, Month, Day) {
    if (Year !== nowYear) {
      await navigateToYear(Year);
    }
    await navigateToMonthAndDay(Month, Day);
    await page.locator('.el-picker-panel__footer .el-button--default').click();
  }
}

// 日期处理函数
async function handleDateSelection(page, value, name) {
  const datePicker = page.locator(`[content="请选择 ${name}"]`);
  await datePicker.click();

  const dateParts = value.split('-'); // 假设日期格式为 YYYY-MM-DD
  const year = parseInt(dateParts[0], 10);
  const month = parseInt(dateParts[1], 10);
  const day = parseInt(dateParts[2], 10);

  // 导航到目标年份和月份
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1; // 月份从0开始

  if (year !== currentYear) {
    const direction = year > currentYear ? 'right' : 'left';
    const yearDiff = Math.abs(year - currentYear);
    for (let i = 0; i < yearDiff; i++) {
      await page.locator(`.el-picker-panel__content.is-${direction} .el-date-picker__header button:visible`).nth(0).click();
    }
  }

  if (month !== currentMonth) {
    const direction = month > currentMonth ? 'right' : 'left';
    const monthDiff = Math.abs(month - currentMonth);
    for (let i = 0; i < monthDiff; i++) {
      await page.locator(`.el-picker-panel__content.is-${direction} .el-date-picker__header button:visible`).nth(1).click();
    }
  }

  // 点击日期
  await page
    .locator(`.el-picker-panel__content .available:visible`)
    .nth(day - 1)
    .click();
  // await page.locator('.el-picker-panel__footer .el-button--default').click();
}
